﻿using FastCloud.Base;
using FastCloud.Base.Config;
using FastCloud.Base.Desgin;
using FastCloud.ORG.DB;
using FastCloud.ORG.Entity;
using FastIOC.Attribute;
using FastORM.Entity;
using FastUtil.Convert;
using FastUtil.Data;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Threading.Tasks;

namespace FastCloud.Controllers.ORG
{
    [Route("frame/org/module")]
    public class ModuleController : BaseController
    {
        [AutoWired]
        private DB_Module DB_Module;
        [AutoWired]
        private DB_ModuleRight DB_ModuleRight;
        [AutoWired]
        private DB_UserRole DB_UserRole;
        [AutoWired]
        private TokenUtil TokenUtil;

        [Route("list")]
        public IActionResult List()
        {
            return View("~/Views/ORG/Module/Module_List.cshtml");
        }

        [Route("add")]
        public IActionResult Add()
        {
            return View("~/Views/ORG/Module/Module_Add.cshtml");
        }

        [Route("edit")]
        public IActionResult Edit()
        {
            return View("~/Views/ORG/Module/Module_Edit.cshtml");
        }

        [Route("oplist"), HttpPost]
        public IActionResult OpList()
        {
            string ModuleName = ValueConvert.ConvertToString(GetFormParam("ModuleName"));
            string ParentModuleGuid = ValueConvert.ConvertToString(GetFormParam("ParentModuleGuid"));
            bool SearchInAll = ValueConvert.ConvertToBoolean(GetFormParam("SearchInAll"));
            string sql = "1=1";
            List<ParamEntity> ParamList = new List<ParamEntity>();
            if (!string.IsNullOrEmpty(ModuleName))
            {
                sql += " and ModuleName like @ModuleName";
                ParamList.Add(new ParamEntity() { ParamName = "ModuleName", ParamValue = "%" + ModuleName + "%" });
            }
            if (!SearchInAll)
            {
                if (!string.IsNullOrEmpty(ParentModuleGuid))
                {
                    sql += " and ParentModuleGuid=@ParentModuleGuid";
                    ParamList.Add(new ParamEntity() { ParamName = "ParentModuleGuid", ParamValue = ParentModuleGuid });
                }
            }
            return Result.OK(DB_Module.SelectPage("*", sql, "SortNum desc", ParamList));
        }

        [Route("opinsert"), HttpPost]
        public IActionResult OpInsert(Frame_Module Entity)
        {
            DB_Module.Insert(Entity);
            return Result.OK();
        }

        [Route("opupdate"), HttpPost]
        public IActionResult OpUpdate(Frame_Module Entity)
        {
            DB_Module.UpdateByID(Entity);
            return Result.OK();
        }

        [Route("opdetail"), HttpPost]
        public IActionResult OpDetail()
        {
            string ModuleGuid = ValueConvert.ConvertToString(GetFormParam("ModuleGuid"));
            return Result.OK(DB_Module.SelectOne(ModuleGuid));
        }

        [Route("opbatchdelete"), HttpPost]
        [Transitional(TransitonLevel = IsolationLevel.ReadUncommitted)]
        public virtual IActionResult OpBatchDelete()
        {
            string KeyID = ValueConvert.ConvertToString(GetFormParam("KeyID"));
            List<string> KeyIDList = KeyID.TrimEnd(';').Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries).ToList();
            foreach (var item in KeyIDList)
            {
                Frame_Module module = DB_Module.SelectOne(item);
                List<ParamEntity> ParamList = new List<ParamEntity>() { new ParamEntity() { ParamName = "ParentModuleGuid", ParamValue = module.ModuleGuid } };
                int SubMoudleCount = DB_Module.SelectCount("ParentModuleGuid=@ParentModuleGuid", ParamList);
                if (SubMoudleCount > 0)
                {
                    return Result.Error(string.Format("模块{0}包含子模块，无法删除", module.ModuleName));
                }
            }
            DB_Module.DeleteBatch(KeyIDList);
            foreach (var item in KeyIDList)
            {
                DB_ModuleRight.DeleteByModuleGuid(item);
            }
            return Result.OK();
        }


        [Route("batchUpdateModulePublicSetting"), HttpPost]
        [Transitional(TransitonLevel = IsolationLevel.ReadUncommitted)]
        public virtual IActionResult BatchUpdateModulePublicSetting()
        {
            string ModuleRightStr = ValueConvert.ConvertToString(GetFormParam("ModuleRightStr"));
            JArray ModuleRightArray = (JArray)JsonConvert.DeserializeObject(ModuleRightStr);
            foreach (JObject item in ModuleRightArray)
            {
                string ModuleGuid = ValueConvert.ConvertToString(item.GetValue("ModuleGuid"));
                int IsPublic = ValueConvert.ConvertToInt32(item.GetValue("IsPublic"));
                DB_Module.UpdateModulePublic(ModuleGuid, IsPublic);
            }
            return Result.OK();
        }

        [Route("tree"), HttpPost]
        public IActionResult Tree()
        {
            List<Frame_Module> ModuleList = DB_Module.SelectAllList();
            ModuleList.Sort((x, y) => -x.SortNum.CompareTo(y.SortNum));
            List<TreeNode> NodeList = new List<TreeNode>();
            Frame_Module Root = new Frame_Module();
            Root.ModuleGuid = "Top";
            Root.ModuleName = "全部模块";
            Root.ParentModuleGuid = "";
            ModuleList.Add(Root);
            foreach (Frame_Module item in ModuleList)
            {
                TreeNode node = new TreeNode();
                node.ID = item.ModuleGuid;
                node.Name = item.ModuleName;
                node.PID = item.ParentModuleGuid;
                if (item.ModuleGuid == Root.ModuleGuid)
                {
                    node.IsTop = true;
                    node.Open = true;
                }
                NodeList.Add(node);
            }
            return Result.OK(CloudUtil.BuildTree(NodeList));
        }

        [Route("getMenuRightTree"), HttpPost]
        public IActionResult GetMenuRightTree()
        {
            //Top:顶部菜单 Left:点击顶部菜单显示的左侧菜单
            string MenuType = ValueConvert.ConvertToString(GetFormParam("MenuType"));
            string ModuleCode = ValueConvert.ConvertToString(GetFormParam("ModuleCode"));

            List<Frame_Module> ModuleList = DB_Module.SelectAllList();
            if (MenuType == "Top")
            {
                //顶级菜单
                ModuleList = ModuleList.Where(a => a.ParentModuleGuid == "Top").ToList();
            }
            else if (MenuType == "Left")
            {
                ModuleList = ModuleList.Where(a => a.ModuleCode.Substring(0, ModuleCode.Length) == ModuleCode && a.ModuleCode != ModuleCode).ToList();
            }
            ModuleList.Sort((x, y) => -x.SortNum.CompareTo(y.SortNum));
            TokenEntity Entity = TokenUtil.GetTokenEntity();
            if (Entity.LoginID != "admin")
            {
                List<Frame_ModuleRight> RightList = DB_ModuleRight.SelectAll();
                List<Frame_UserRole> UserRoleList = DB_UserRole.SelectAll().Where(a => a.UserGuid == Entity.UserGuid).ToList();
                List<string> RoleGuidList = UserRoleList.Select(a => a.RoleGuid).ToList();
                List<Frame_ModuleRight> RightFilterList = RightList.Where(a =>
                    (a.RightGuid == Entity.OUGuid && a.RightType == (int)FastCloud.Base.Enum.ORG.RightType.部门) ||
                    (a.RightGuid == Entity.UserGuid && a.RightType == (int)FastCloud.Base.Enum.ORG.RightType.人员) ||
                    (RoleGuidList.Contains(a.RightGuid) && a.RightType == (int)FastCloud.Base.Enum.ORG.RightType.角色)).ToList();
                List<string> ModuleGuidList = RightFilterList.Select(a => a.ModuleGuid).ToList();
                List<Frame_Module> AllModuleCopyList = CopyUtil.CopyList<Frame_Module>(ModuleList).Where(a => ModuleGuidList.Contains(a.ModuleGuid) || a.IsPublic == (int)FastCloud.Base.Enum.ORG.IsPublic.完全公开).ToList();
                //对于子菜单有权限而父级菜单未赋值权限的，需要自动补齐
                for (int i = 0; i < AllModuleCopyList.Count; i++)
                {
                    Frame_Module Module = AllModuleCopyList[i];
                    if (Module.ParentModuleGuid != "Top")
                    {
                        //如果不是顶级菜单就要验证本菜单的父级菜单是否在菜单列表中
                        List<Frame_Module> AllModuleCopyListCopy = AllModuleCopyList.Where(a => a.ModuleGuid == Module.ParentModuleGuid).ToList();
                        if (AllModuleCopyListCopy.Count == 0)
                        {
                            AllModuleCopyList.Add(ModuleList.Where(a => a.ModuleGuid == Module.ParentModuleGuid).ToList()[0]);
                            i = 0;
                        }
                    }
                }
                ModuleList = AllModuleCopyList.OrderByDescending(a => a.SortNum).ToList();
            }

            List<TreeNode> NodeList = new List<TreeNode>();
            foreach (Frame_Module item in ModuleList)
            {
                TreeNode node = new TreeNode();
                node.ID = item.ModuleGuid;
                node.Name = item.ModuleName;
                node.PID = item.ParentModuleGuid;
                if (MenuType == "Left")
                {
                    if (item.ModuleCode.Length == ModuleCode.Length + 4)
                    {
                        node.IsTop = true;
                        node.Open = true;
                    }
                }
                else
                {
                    if (item.ParentModuleGuid == "Top")
                    {
                        node.IsTop = true;
                        node.Open = true;
                    }
                }

                node.AddExtra("ModuleCode", item.ModuleCode);
                node.AddExtra("ModuleUrl", item.ModuleUrl);
                node.AddExtra("ModuleIcon", item.ModuleIcon);
                NodeList.Add(node);
            }
            return Result.OK(CloudUtil.BuildTree(NodeList));
        }
    }
}
